package com.zzh.partnersys.im.handler;

import com.google.gson.Gson;
import com.zzh.partnersys.im.message.WSMessage;
import com.zzh.partnersys.im.message.request.*;
import com.zzh.partnersys.im.message.response.ApplyAddFriendResponseMessage;
import com.zzh.partnersys.im.session.SessionFactory;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.*;
import io.netty.util.AttributeKey;

/**
 * @author �?�?�?
 * @version 1.0
 */
//TextWebSocketFrame表示一个文本帧
public class MyTextWebSocketFrameHandler extends SimpleChannelInboundHandler<WebSocketFrame> {
    Gson gson = new Gson();

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, WebSocketFrame frame) throws Exception {
        if (frame instanceof TextWebSocketFrame){//处理文本�?
            TextWebSocketFrame textWebSocketFrame = (TextWebSocketFrame) frame;
            System.out.println("服务端接收到消息"+textWebSocketFrame.text());
            //json字符串转�?
            String jsonStr = textWebSocketFrame.text();//比如登录绑定{"type":0,"uid":1}
            System.out.println("jsonStr"+jsonStr);
            WSMessage wsMessage = gson.fromJson(jsonStr, WSMessage.class);
            System.out.println("wsMessage"+wsMessage);
            if (wsMessage != null){
                int wsMType = wsMessage.getType();
                Long uid = 0L;
                Long toUid = 0L;
                String content = "";
                Long teamId = 0L;
                String fromName;//用户好友申请同意后插入数据使�?
                String toName;//用户好友申请同意后插入数据使�?
                switch (wsMType){
                    case 0: //登录绑定Channel 不需要登录绑定了，直接ws发送连接携带用户参数！
                        System.out.println("进入登录绑定");
                        uid = wsMessage.getUid();
                        LoginRequestBindMessage loginRequestBindMessage = new LoginRequestBindMessage(uid);

                        // 将新的消息传递给下一�?Handler
                        ctx.fireChannelRead(loginRequestBindMessage);
                        break;
                    case 1: // 解绑Channel
                        System.out.println("进入解除绑定");
                        uid = wsMessage.getUid();
                        LoginRequestNotBindMessage loginRequestNotBindMessage = new LoginRequestNotBindMessage(uid);
                        // 将新的消息传递给下一�?Handler
                        ctx.fireChannelRead(loginRequestNotBindMessage);
                        break;
                    case 2: //好友申请列表
                        System.out.println("进入好友申请");
                        uid = wsMessage.getUid();
                        toUid = wsMessage.getToUid();//找到给那个用户发送消�?
                        content = wsMessage.getContent();//好友申请的消息内�?
                        ApplyAddFriendRequestMessage applyAddFriendRequestMessage = new ApplyAddFriendRequestMessage(uid,toUid, content);
                        // 将新的消息传递给下一�?Handler
                        ctx.fireChannelRead(applyAddFriendRequestMessage);
                        break;
                    case 3: //好友申请列表回复
                        System.out.println("进入好友申请回复");
                        uid = wsMessage.getUid();
                        toUid = wsMessage.getToUid();//找到给那个用户发送消�?
                        content = wsMessage.getContent();//好友申请的消息内�?
                        fromName = wsMessage.getFromName();
                        toName = wsMessage.getToName();
                        ApplyAddFriendResponseMessage applyAddFriendResponseMessage = new ApplyAddFriendResponseMessage(uid,toUid,content,fromName,toName);
                        // 将新的消息传递给下一�?Handler
                        ctx.fireChannelRead(applyAddFriendResponseMessage);
                        break;
                    case 4: // 私聊-文本
                        System.out.println("进入私聊");
                        uid = wsMessage.getUid();
                        toUid = wsMessage.getToUid();//找到给那个用户发送消�?
                        content = wsMessage.getContent();//消息内容
                        ChatRequestMessage chatRequestMessage = new ChatRequestMessage(uid,toUid, content);
                        // 将新的消息传递给下一�?Handler
                        System.out.println(chatRequestMessage);
                        ctx.fireChannelRead(chatRequestMessage);
                        break;
                    case 5://群聊-文本
                        System.out.println("进入群聊");
                        uid = wsMessage.getUid();//谁发消息
                        teamId = wsMessage.getTeamId();//发给哪个�?
                        content = wsMessage.getContent();//消息内容
                        TeamChatRequestMessage teamChatRequestMessage = new TeamChatRequestMessage(uid, teamId, content);
                        System.out.println(teamChatRequestMessage);
                        // 将新的消息传递给下一�?Handler
                        ctx.fireChannelRead(teamChatRequestMessage);
                        break;
                    case 6://单聊-表情�?
                        System.out.println("进入单聊-表情");
                        uid = wsMessage.getUid();//谁发消息
                        toUid = wsMessage.getToUid();//找到给那个用户发送消�?
                        content = wsMessage.getContent();//消息内容
                        ChatEmojiRequestMessage chatEmojiRequestMessage = new ChatEmojiRequestMessage(uid, toUid, content);
                        System.out.println(chatEmojiRequestMessage);
                        // 将新的消息传递给下一�?Handler
                        ctx.fireChannelRead(chatEmojiRequestMessage);
                        break;
                    case 7://群聊-表情
                        System.out.println("进入群聊-表情");
                        uid = wsMessage.getUid();//谁发消息
                        teamId = wsMessage.getTeamId();//发给哪个�?
                        content = wsMessage.getContent();//消息内容
                        TeamChatEmojiRequestMessage teamChatEmojiRequestMessage = new TeamChatEmojiRequestMessage(uid, teamId, content);
                        System.out.println(teamChatEmojiRequestMessage);
                        // 将新的消息传递给下一�?Handler
                        ctx.fireChannelRead(teamChatEmojiRequestMessage);
                        break;
                    case 8://单聊-邀请加入队伍
                        System.out.println("进入单聊-邀请加入队伍");
                        uid = wsMessage.getUid();//谁发消息
                        content = wsMessage.getContent();//消息内容->队伍头像
                        toUid = wsMessage.getToUid();
                        InviteAddTeamRequestMessage inviteAddTeamRequestMessage = new InviteAddTeamRequestMessage(uid, toUid, content);
                        System.out.println(inviteAddTeamRequestMessage);
                        // 将新的消息传递给下一�?Handler
                        // 将新的消息传递给下一�?Handler
                        ctx.fireChannelRead(inviteAddTeamRequestMessage);
                        break;
                }
            }
        }else if (frame instanceof PingWebSocketFrame) {
            ctx.channel().writeAndFlush(new PongWebSocketFrame(frame.content().retain()));
        } else if (frame instanceof CloseWebSocketFrame) {
            ctx.close();
        }

    }

    //当web客户端连接后触发该方法（连接成功，绑定channel�?
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        //这里去建立连�?绑定用户id)
        System.out.println("handlerAdded 被调�?"+ctx.channel().id().asLongText());
        System.out.println("handlerAdded 被调�?"+ctx.channel().id().asShortText());
        String userId = ctx.channel().attr(AttributeKey.<String>valueOf("userId")).get();
        System.out.println("连接成功拿到的userId"+userId);
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        //id表示唯一 longText是唯一�?shortText不是惟一�?
        System.out.println("handlerRemoved 被调�?"+ctx.channel().id().asLongText());
        System.out.println("handlerRemoved 被调�?"+ctx.channel().id().asShortText());
        //同时解绑
        SessionFactory.getSession().unbind(ctx.channel());
        //关闭连接
        ctx.close();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("异常发生 "+cause.getMessage());
        //同时解绑
        SessionFactory.getSession().unbind(ctx.channel());
        //关闭连接
        ctx.close();
    }

    //断开连接
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("客户端与服务端断开连接");
        //同时解绑
        SessionFactory.getSession().unbind(ctx.channel());
        //关闭连接
        ctx.close();
    }
}
